package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private MinioClient minioClient ;

    @Autowired
    private MinioProperties minioProperties;

    @Override
    public String upload(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {

        String bucketName = minioProperties.getBucketName();

        //1.判断桶是否存在，不存在则创建，定义桶访问策略
        boolean flag = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if(!flag){
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            String config = """
                    {
                      "Statement" : [ {
                        "Action" : "s3:GetObject",
                        "Effect" : "Allow",
                        "Principal" : "*",
                        "Resource" : "arn:aws:s3:::%s/*"
                      } ],
                      "Version" : "2012-10-17"
                    }
                    """.formatted(bucketName);
            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder()
                    .bucket(bucketName)
                    .config(config)
                    .build());
        }
        //2.文件转存(uploadObject(),putObject())
        minioClient.putObject(PutObjectArgs
                .builder()
                        .bucket(bucketName)
                        .object(file.getOriginalFilename())
                        .contentType(file.getContentType())
                        .stream(file.getInputStream(),file.getSize(),-1)
                .build());

        //3.返回URL
        // endPoint + "/" + URI(bucketName+"/"+fileName)
        //return minioProperties.getEndpoint()+"/"+minioProperties.getBucketName()+"/"+file.getOriginalFilename();
        return String.join(File.separator, minioProperties.getEndpoint(), minioProperties.getBucketName(),file.getOriginalFilename());
    }
}
